package com.quanquan.user.message;

import com.quanquan.user.request.IntegralDetailsRequestBody;
import com.quanquan.user.service.IntegralTradingDetailsService;
import com.rabbitmq.client.Channel;
import commond.IntegralOutPut;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 功能描述:接收其他模块传来的消费积分的数据
 *
 * @ClassName: MqImageReceiver
 * @Author: xiaoqianh丶
 * @Date: 2019-03-13 14:07
 * @Version: V1.0
 */
@Slf4j
@Component
public class MqIntegralReceiver {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    private final IntegralTradingDetailsService integralTradingDetailsService;

    @Autowired
    public MqIntegralReceiver(IntegralTradingDetailsService imageService) {
        this.integralTradingDetailsService = imageService;
    }

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "integralDetails",
                    durable = "true"),
            exchange = @Exchange(value = "integral.exchange",
                    type = "topic"),
            ignoreDeclarationExceptions = "true",
            key = "integral.#")})
    @RabbitHandler
    public void updateIntegralInfo(@Payload IntegralOutPut integralOutPut,
                                   Channel channel,
                                   @Headers Map<String, Object> headers) throws IOException {
        IntegralDetailsRequestBody requestBody = new IntegralDetailsRequestBody();

        //手工ack
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);


        //通过映射关系来赋值 //TODO 断点看一下
        BeanUtils.copyProperties(integralOutPut, requestBody);
        integralTradingDetailsService.createIntegralDetails(requestBody);
    }


}
